package com.kaichaohulian.baocms.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kaichaohulian.baocms.NearService;
import com.kaichaohulian.baocms.R;
import com.kaichaohulian.baocms.activity.FriendInfoActivity;
import com.kaichaohulian.baocms.activity.GreetActivity;
import com.kaichaohulian.baocms.adapter.NearbyListAdapter;
import com.kaichaohulian.baocms.app.MyApplication;
import com.kaichaohulian.baocms.base.BaseFragment;
import com.kaichaohulian.baocms.ecdemo.common.utils.ToastUtil;
import com.kaichaohulian.baocms.entity.CommonEntity;
import com.kaichaohulian.baocms.entity.GreetBean;
import com.kaichaohulian.baocms.entity.NearbyBean;
import com.kaichaohulian.baocms.http.HttpArray;
import com.kaichaohulian.baocms.http.HttpResult;
import com.kaichaohulian.baocms.retrofit.RetrofitClient;
import com.kaichaohulian.baocms.rxjava.BaseListObserver;
import com.kaichaohulian.baocms.rxjava.BaseObjObserver;
import com.kaichaohulian.baocms.rxjava.RxUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by gaoyuan on 2017/5/4.
 */
@SuppressLint("ValidFragment")
public class DiscoverFragment2 extends BaseFragment implements View.OnClickListener, BaseQuickAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.bt_nearby_show)
    Button btNearbyShow;
    @BindView(R.id.rv_nearby_list)
    RecyclerView rvNearbyList;
    @BindView(R.id.refresh_nearby)
    SwipeRefreshLayout refreshNearby;
    @BindView(R.id.img_nearby_avatar)
    ImageView imgNearbyAvatar;
    @BindView(R.id.tv_nearby_num)
    TextView tvNearbyNum;
    @BindView(R.id.ll_nearby_notify)
    LinearLayout llNearbyNotify;
    @BindView(R.id.img_nearby_img)
    ImageView imgNearbyImg;
    @BindView(R.id.rl_near_list)
    LinearLayout rlNearList;

    ImageView img_pop;

    private NearbyListAdapter mAdapter;
    private List<NearbyBean> mList;
    private TextView tvGirl, tvBoy, tvAll, tvGreet, tvClear, tvCancel;
    private LinearLayout popLayout;
    private PopupWindow popupWindow;


    public DiscoverFragment2(MyApplication myApplication, Activity activity, Context context) {
        super(myApplication, activity, context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.activity_nearby_zy, null);
        ButterKnife.bind(this, view);
        getActivity().startService(new Intent(getActivity(), NearService.class));
     /*   img_pop = (ImageView) view.findViewById(R.id.img_pop);
        img_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                showPopupWindow(img_pop);
            }
        });
        try {

            mList = new ArrayList<>();
            rvNearbyList.setLayoutManager(new LinearLayoutManager(getActivity()));
            mAdapter = new NearbyListAdapter(R.layout.item_neayby_list, mList);
            rvNearbyList.setAdapter(mAdapter);
            try {
//                getNearUser(1, 2);
                getNearUser(1, 2);
                mAdapter.setOnItemClickListener(this);
                refreshNearby.setOnRefreshListener(this);
            } catch (Exception e) {
                e.printStackTrace();
            }

            onRefresh();

        } catch (Exception e) {
            e.printStackTrace();
        }*/
        return view;
    }


    @Override
    public void setContent() {

    }

    @Override
    public void initData() {
//        new TitleUtils(getActivity()).setTitle("附近的人");
        loadGreetList();
        try {
            getNearUser(1, 2);
            mAdapter.setOnItemClickListener(this);
            refreshNearby.setOnRefreshListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        onRefresh();
    }

    public Map<String, String> map;
    private GreetBean mGreetBean;

    private void loadGreetList() {
        map.put("id", MyApplication.getInstance().UserInfo.getUserId() + "");
        map.put("page", "1");
        RetrofitClient.getInstance().createApi().greetList(map)
                .compose(RxUtils.<HttpResult<GreetBean>>io_main())
                .subscribe(new BaseObjObserver<GreetBean>(getActivity(), false) {
                    @Override
                    protected void onHandleSuccess(GreetBean greetBean) {
                        if (greetBean == null) {
                            return;
                        }
                        if (greetBean.getRequestDTOs1() != null && greetBean.getRequestDTOs1().size() > 0) {
//                            llNearbyNotify.setVisibility(View.VISIBLE);
                            mGreetBean = greetBean;
                          /*  tvChatNums.setText("你收到" + greetBean.getRembers() + "条新的打招呼");
                            if (mGreetBean.getRembers() > 0) {
                                Glide.with(NearbyZyActivity.this)
                                        .load(greetBean.getRequestDTOs1().get(0).getAvatar())
                                        .error(R.mipmap.default_useravatar)
                                        .into(imgNearbyAvatar);

                            }*/
                        }
                    }
                });
    }

    @Override
    public void initView() {

    }

    @Override
    public void initEvent() {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {

    }

    private void showPopupWindow(View parent) {
        if (popupWindow == null) {

            View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_near, null);
//            View view = LayoutInflater.from(getActivity()).inflate(R.layout.pop_nearby_list, null);
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        //设置动画效果
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取popwindow焦点
        popupWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop(View view) {
        popLayout = (LinearLayout) view.findViewById(R.id.ll_pop_near_out);
        tvGirl = (TextView) view.findViewById(R.id.ll_pop_near_girl);
        tvBoy = (TextView) view.findViewById(R.id.ll_pop_near_boy);
        tvAll = (TextView) view.findViewById(R.id.ll_pop_near_all);
        tvGreet = (TextView) view.findViewById(R.id.ll_pop_near_greet);
        tvClear = (TextView) view.findViewById(R.id.ll_pop_near_clear);
        tvCancel = (TextView) view.findViewById(R.id.ll_pop_near_cancel);

        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);

        popLayout.setOnClickListener(this);
        tvAll.setOnClickListener(this);
        tvBoy.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        tvClear.setOnClickListener(this);
        tvGirl.setOnClickListener(this);
        tvGreet.setOnClickListener(this);
    }


    private void getNearUser(int page, int sex) {

      /*  final RequestParams params = new RequestParams();
        params.put("id", MyApplication.getInstance().UserInfo.getUserId() + "");

  *//*      params.put("longitud", MyApplication.lng);
        params.put("latitude", MyApplication.lat);*//*
        params.put("longitud", "40.04016");
        params.put("latitude", "116.296276");
        params.put("page", page + "");
        params.put("sex", sex + "");//0 男 1女 2全部

        HttpUtil.post(Url.near, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d(response.toString(), "333333333333333333");


            }

            @Override
            public void onFinish() {
                ShowDialog.dissmiss();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                DBLog.e("tag", statusCode + ":" + responseString);
                ShowDialog.dissmiss();
//                Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
//                Toast.makeText(getActivity(), "请求取消", Toast.LENGTH_SHORT).show();
            }
        });*/
        Map<String, String> map = new HashMap<>();
        map.put("id", MyApplication.getInstance().UserInfo.getUserId() + "");
//        map.put("userId", MyApplication.getInstance().UserInfo.getUserId() + "");
        map.put("longitud", MyApplication.lng);
        map.put("latitude", MyApplication.lat);
      /*  map.put("longitud", "40.04016");
        map.put("latitude", "116.296276");*/
        map.put("page", page + "");
        map.put("sex", sex + "");//0 男 1女 2全部
        RetrofitClient.getInstance().createApi().getNearUser(map)
                .compose(RxUtils.<HttpArray<NearbyBean>>io_main())
                .subscribe(new BaseListObserver<NearbyBean>(getActivity(), "加载中", refreshNearby) {
                    @Override
                    protected void onHandleSuccess(List<NearbyBean> list) {

                        for (NearbyBean nearbyBean : list) {
                            Log.d("NearbyListActivity", nearbyBean.toString());
                        }
                        mList.clear();
                        mList.addAll(list);
                        mAdapter.notifyDataSetChanged();


                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getActivity(), "失败", Toast.LENGTH_SHORT).show();
                    }
                });

    }
        /*   Map<String, String> map = new HashMap<>();
        map.put("id", MyApplication.getInstance().UserInfo.getUserId() + "");
        map.put("userId", MyApplication.getInstance().UserInfo.getUserId() + "");
        map.put("longitud", MyApplication.lng);
        map.put("latitude", MyApplication.lat);
        map.put("page", page + "");
        map.put("sex", sex + "");//0 男 1女 2全部
        RetrofitClient.getInstance().createApi().getNearUser(map)
                .compose(RxUtils.<HttpArray<NearbyBean>>io_main())
                .subscribe(new BaseListObserver<NearbyBean>(getActivity(), "加载中", refreshNearby) {
                    @Override
                    protected void onHandleSuccess(List<NearbyBean> list) {
                        Toast.makeText(getActivity(), "成功", Toast.LENGTH_SHORT).show();
                        for (NearbyBean nearbyBean : list) {
                            Log.d("NearbyListActivity", nearbyBean.toString());
                        }
                        mList.clear();
                        mList.addAll(list);
                        mAdapter.notifyDataSetChanged();


                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getActivity(), "失败", Toast.LENGTH_SHORT).show();
                    }
                });
*/


    @Override
    public void onDestroyView() {
        super.onDestroyView();


    }

    @Override
    public void onRefresh() {
//        getNearUser(1, 2);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_pop_near_out:
                break;
            case R.id.ll_pop_near_girl:
                getNearUser(1, 1);
                break;
            case R.id.ll_pop_near_boy:
                getNearUser(1, 0);
                break;
            case R.id.ll_pop_near_all:
                getNearUser(1, 2);
                break;
            case R.id.ll_pop_near_greet:
                startActivity(new Intent(getActivity(), GreetActivity.class));
                break;
            case R.id.ll_pop_near_clear:
                clearLocation();
                break;
            case R.id.ll_pop_near_cancel:
                popupWindow.dismiss();
                break;
        }
        popupWindow.dismiss();
    }

    /**
     * 清空位置信息
     */
    private void clearLocation() {
        RetrofitClient.getInstance().createApi()
                .clearLocation(MyApplication.getInstance().UserInfo.getUserId())
                .compose(RxUtils.<HttpResult<CommonEntity>>io_main())
                .subscribe(new BaseObjObserver<CommonEntity>(getActivity(), "清除信息中") {
                    @Override
                    protected void onHandleSuccess(CommonEntity commonEntity) {
                        ToastUtil.showMessage("清除位置信息成功");
                        getActivity().stopService(new Intent(getActivity(), NearService.class));
//                        AppManager.getAppManager().finishActivity(NearbyZyActivity.class);
//                        finish();
                    }
                });
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = new Intent(getActivity(), FriendInfoActivity.class);
        intent.putExtra("phone", mList.get(position).getPhone() + "");
        intent.putExtra("friendId", mList.get(position).getUserId() + "");
        intent.putExtra("type", "3");
        startActivity(intent);
    }

    @OnClick(R.id.bt_nearby_show)
    public void onViewClicked() {
    }

   /* @OnClick({R.id.img_nearby_avatar, R.id.tv_nearby_num, R.id.ll_nearby_notify, R.id.img_nearby_img, R.id.bt_nearby_show})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.img_nearby_avatar:
                break;
            case R.id.tv_nearby_num:
                break;
            case R.id.ll_nearby_notify:
                if (mGreetBean == null) {
                    return;
                }
                Intent intent = new Intent(getActivity(), GreetActivity.class);
                startActivity(intent);
                break;
            case R.id.img_nearby_img:
                break;
            case R.id.bt_nearby_show:
                startActivity(new Intent(getActivity(), NearbyListActivity.class));
                break;
        }
    }*/
}
